import React from 'react';
import { Row, Col } from 'antd';
import { assetStatistic } from '@/services/Collection';
import styles from './index.less';
import CountUp from 'react-countup';

const countUpProps = {
  star: 0,
  duration: 2.75,
  useEasing: true,
  useGrouping: true,
  separator: ','
}

const Info = (props) => {
  return (
    <div className={styles.mainContainer}>
      <span>{props.title}</span>
      <p><CountUp end={props.value} {...countUpProps} decimals={props.isTotal ? '2' : ''} /></p>
      {props.bordered && <em />}
    </div>
  )
}

class Statistic extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      query: {},
      statistic: {}
    }
  }

  /* 获取数据详情 */
  getAssetStatistic = async () => {
    try {
      const query = this.state.query || {};
      const res = await assetStatistic(query);
      this.setState({ statistic: res });
    } catch (e) {
      console.error(e)
    }
  }

  componentDidMount() {
    this.getAssetStatistic();
  }

  componentDidUpdate(prevProps) {
    const query = this.state.query;
    if (JSON.stringify(prevProps.query) !== JSON.stringify(query)) {
      this.getAssetStatistic();
    }
  }

  /* 监听父级数据变化 */
  static getDerivedStateFromProps(props, state) {
    const query = props.query;
    const preQuery = state.query;
    if (JSON.stringify(query) !== JSON.stringify(preQuery)) {
      return { query }
    }
    return null
  }

  render() {
    const { biblioQuantity, itemQuantity, statusQuantity, totalAmount } = this.state.statistic;
    let inBook = 0,
      outBook = 0,
      returnBook = 0,
      initBook = 0,
      unBook = 0;
    if (totalAmount > 0) {
      inBook = statusQuantity[1];
      outBook = statusQuantity[2];
      returnBook = statusQuantity[3];
      initBook = statusQuantity[5];
      unBook = statusQuantity[10];
    }
    return (
      <Row>
        <Col sm={3} xs={12}>
          <Info title="在馆图书" value={inBook} bordered />
        </Col>
        <Col sm={3} xs={12}>
          <Info title="借阅图书" value={outBook} bordered />
        </Col>
        <Col sm={3} xs={24}>
          <Info title="归还图书" value={returnBook} bordered />
        </Col>
        <Col sm={3} xs={12}>
          <Info title="未加工图书" value={initBook} bordered />
        </Col>
        <Col sm={3} xs={12}>
          <Info title="注销图书" value={unBook} bordered />
        </Col>
        <Col sm={3} xs={12}>
          <Info title="图书数目种类" value={biblioQuantity} bordered />
        </Col>
        <Col sm={3} xs={12}>
          <Info title="书本册数" value={itemQuantity} bordered />
        </Col>
        <Col sm={3} xs={12}>
          <Info title="总金额" value={totalAmount} isTotal={true}/>
        </Col>
      </Row>
    );
  }
}

export default Statistic;
